package edu.buaa.traffic;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.aliyun.log.producer.errors.ProducerException;
import edu.buaa.common.TxResultProcessor;
import edu.buaa.common.client.DBProxy;
import edu.buaa.common.client.TGraphExecutorClient;
import edu.buaa.common.client.Neo4jExecutorClient;
import edu.buaa.common.transaction.AbstractTransaction;
import edu.buaa.common.transaction.CreateTGraphAggrMaxIndexTx;
import edu.buaa.common.transaction.CreateTGraphTemporalValueIndexTx;
import edu.buaa.traffic.client.MariaDBExecutorClient;
import edu.buaa.traffic.client.PostgreSQLExecutorClient;
import edu.buaa.traffic.transaction.ImportStaticDataTx;
import edu.buaa.traffic.transaction.ImportTemporalDataTx;
import edu.buaa.traffic.transaction.index.CreateTGraphAggrDurationIndexTx;
import edu.buaa.utils.Helper;
import edu.buaa.utils.TimeTicker;

import java.io.File;
import java.io.IOException;
import java.util.*;

import static edu.buaa.traffic.TrafficTxGenerator.monthDayStr2Time;

public class MilestoneBuilder {
    private static final String dataset = Helper.mustEnv("DATASET");
    private static final String dbType = Helper.mustEnv("DB_TYPE");
    private static final String serverHost = Helper.mustEnv("DB_HOST"); // hostname of server.
    private static final String dataPath = Helper.mustEnv("DATA_PATH"); // should be like '/media/song/test/data-set/beijing-traffic/TGraph/byday/'
    private static final String tpRange = Helper.mustEnv("TP_RANGE").split("_")[1]; //20120101
    private static final String startDay = tpRange.split("-")[0];
    private static final String endDay = tpRange.split("-")[1];
    private static final int temporalDataPerTx = 200; //Integer.parseInt(Helper.mustEnv("TEMPORAL_DATA_PER_TX"));

    static {
        System.out.println("build time set to "+startDay+" ~ "+endDay);
        assert dataset.equals("traffic");
    }

//    private static Producer logger;
    private static DBProxy client;
    private static TxResultProcessor post;
    private static TrafficTxGenerator.TemporalPropertyAppendTxGenerator iterator;

    public static void main(String[] args){
        try {
            client = initClient(dbType, serverHost, 1);
            client.testServerClientCompatibility();
            String codeVersion = Helper.codeGitVersion();
            post = new TxResultProcessor(getTestName(dbType), codeVersion);
//            logger = Helper.getLogger();
//            post.setLogger(logger);
            importStatic();
            importTemporal();
            close();
            System.exit(0);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    private static void importStatic() throws Exception {
        System.out.print("import static data...");
        TrafficTxGenerator txGen = new TrafficTxGenerator(new File(dataPath, dataset));
        ImportStaticDataTx txStaticImport = txGen.txImportStatic();
        client.execute(txStaticImport).get();

        iterator = txGen.temporalTx(startDay, endDay, temporalDataPerTx);
        System.out.println("done\nimport temporal data...");
        if(iterator.hasNext() && "tgraph_kernel".equals(dbType)){
            ImportTemporalDataTx tx = iterator.next();
            post.processSync(client.execute(tx), tx);
            createTGraphIndexes();
        }
    }

    private static void createTGraphIndexes() throws Exception {
        int tBegin = (int) (monthDayStr2Time(startDay) / 1000);
        int tFinish = (int) (monthDayStr2Time(endDay)/ 1000);
        createIndex(max("travel_time", tBegin, tFinish, 1, Calendar.DATE));
        createIndex(dur("full_status", tBegin, tFinish, 1, Calendar.DATE));
        createIndex(tv("travel_time", tBegin, tFinish));
    }

    public static void importTemporal() throws Exception {
        TimeTicker lastTick = new TimeTicker(60, 100);
        while (iterator.hasNext()) {
            ImportTemporalDataTx tx = iterator.next();
            if(lastTick.shouldTick()) System.out.println(JSON.toJSONString(tx.data.get(0)));
            post.process(client.execute(tx), tx);
        }
    }

    public static void close() throws IOException, InterruptedException, ProducerException {
        System.out.println("import temporal data done.");
        client.close();
        post.close();
//        logger.close();
    }

    public static DBProxy initClient(String dbType, String dbHost, int maxConnCnt) throws Exception {
        switch (dbType.toLowerCase()) {
            case "mariadb": return new MariaDBExecutorClient(dbHost, maxConnCnt);
            case "postgresql": return new PostgreSQLExecutorClient(dbHost, maxConnCnt);
            case "tgraph_kernel": return new TGraphExecutorClient(dbHost, maxConnCnt);
            case "neo4j1": return new Neo4jExecutorClient(dbHost, 5844, maxConnCnt);
            case "neo4j2": return new Neo4jExecutorClient(dbHost, 5833, maxConnCnt);
            default:
                throw new UnsupportedOperationException();
        }
    }

    public static String getTestName(String dbType){
        Calendar c = Calendar.getInstance();
        return "M_"+c.get(Calendar.YEAR)+"."+(c.get(Calendar.MONTH)+1)+"."+c.get(Calendar.DAY_OF_MONTH)+"_"+
                c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+dbType.toLowerCase();
    }


    private static void createIndex(AbstractTransaction tx) throws Exception {
        System.out.println(JSON.toJSONString(tx));
        long begin = System.currentTimeMillis();
        post.processSync(client.execute(tx), tx);
        System.out.println("index created in "+(System.currentTimeMillis()-begin)+" ms");
        System.out.println();
    }

    private static CreateTGraphAggrMaxIndexTx max(String propName, int begin, int end, int every, int timeUnit ){
        CreateTGraphAggrMaxIndexTx tx = new CreateTGraphAggrMaxIndexTx();
        tx.setProName(propName);
        tx.setStart(begin);
        tx.setEnd(end);
        tx.setEvery(every);
        tx.setTimeUnit(timeUnit);
        return tx;
    }

    private static CreateTGraphAggrDurationIndexTx dur(String propName, int begin, int end, int every, int timeUnit){
        CreateTGraphAggrDurationIndexTx tx = new CreateTGraphAggrDurationIndexTx();
        tx.setProName(propName);
        tx.setStart(begin);
        tx.setEnd(end);
        tx.setEvery(every);
        tx.setTimeUnit(timeUnit);
        return tx;
    }

    private static CreateTGraphTemporalValueIndexTx tv(String propName, int begin, int end){
        CreateTGraphTemporalValueIndexTx tx = new CreateTGraphTemporalValueIndexTx();
        tx.setProps(Collections.singletonList(propName));
        tx.setStart(begin);
        tx.setEnd(end);
        return tx;
    }
}
